<template>
  <MainLayout title="用户管理">
    <template #main>
      <div class="main_block">
        <SearchLayout>
          <template #search>
            <el-input
              v-model="search_params.queryParams.userName"
              placeholder="请输入用户名"
              clearable
              class="search_item"
            />
            <el-input
              v-model="search_params.queryParams.userAccount"
              placeholder="请输入账号"
              clearable
              class="search_item"
            />
            <el-select
              v-model="search_params.queryParams.userStatus"
              placeholder="请选择禁用状态"
              class="search_item"
              clearable
            >
              <el-option
                class="select_item"
                v-for="item in state_options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button type="primary" @click="handleSearchList('saerch')"
              >搜索</el-button
            >
            <el-button @click="handleSearchReset">重置</el-button>
            <el-button type="success" @click="handleAddUser"
              >新增用户</el-button
            >
          </template>
          <template #table>
            <el-table
              :data="table_list"
              border
              v-loading="table_loading"
              :style="{ height: 'calc(100vh - 260px)' }"
            >
              <el-table-column
                prop="userName"
                label="用户名"
                min-width="180"
                align="center"
              />
              <el-table-column
                prop="userAccount"
                label="账号"
                min-width="120"
                align="center"
              />
              <el-table-column
                prop="userRole"
                label="角色"
                min-width="120"
                align="center"
              >
                <template #default="{ row }">
                  {{ row.userRole == "admin" ? "管理员" : "普通用户" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="createTime"
                label="创建时间"
                min-width="120"
                align="center"
              >
                <template #default="{ row }">
                  {{ iso8601ToTime(row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="userStatus"
                label="是否禁用"
                min-width="100"
                align="center"
              >
                <template #default="{ row }">
                  <el-switch
                    :model-value="row.userStatus"
                    size="small"
                    active-value="-1"
                    inactive-value="1"
                    @change="handleStatusChange(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="100"
                fixed="right"
                align="center"
              >
                <template #default="{ row }">
                  <div class="flex_block_around operate_block">
                    <div
                      class="color_primary cursor_pointer"
                      @click="handleEditUser(row)"
                    >
                      编辑
                    </div>
                    <div
                      class="color_delete cursor_pointer"
                      @click="handleDelete(row)"
                    >
                      删除
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <Pagination
              :page="search_params.pageNum"
              :size="search_params.pageSize"
              :total="table_total"
              @change="handlePaginationChange"
            ></Pagination>
          </template>
        </SearchLayout>
      </div>
    </template>
  </MainLayout>
  <el-dialog
    v-model="isShowDialog"
    :title="`${dialog_state ? '新增' : '编辑'}用户`"
    width="500"
    :before-close="handleDialogClose"
    :close-on-click-modal="false"
  >
    <div class="dialog_main">
      <el-form
        ref="form_ref"
        :model="form_params"
        label-width="100"
        :rules="form_rules"
        style="max-width: 500px"
      >
        <el-form-item label="用户名：" prop="userName">
          <el-input
            v-model="form_params.userName"
            clearable
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="角色：" prop="userRole">
          <el-radio-group v-model="form_params.userRole">
            <el-radio
              v-for="item in role_list"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号：" prop="userAccount">
          <el-input
            v-model="form_params.userAccount"
            clearable
            placeholder="请输入账号"
          />
        </el-form-item>
        <el-form-item label="密码：" prop="userPasswd" v-if="dialog_state">
          <el-input
            v-model="form_params.userPasswd"
            clearable
            placeholder="请输入密码"
            show-password
            type="password"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button
          type="primary"
          :loading="form_loading"
          @click="handleDialogConfirm"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  AdminUserList,
  AdminUserAdd,
  AdminUserEdit,
  AdminUserDelete,
} from "@/api/user.js";
import { nextTick, ref } from "vue";
import { iso8601ToTime } from "@/utils/index.js";

const search_params = reactive({
  queryParams: {
    userName: "",
    userAccount: "",
    userStatus: "",
  },
  pageNum: 1,
  pageSize: 10,
});
const state_options = [
  {
    label: "启用",
    value: "1",
  },
  {
    label: "禁用",
    value: "-1",
  },
];
const table_total = ref(0);
const table_loading = ref(false);
const table_list = ref([]);
const isShowDialog = ref(false);
const dialog_state = ref(true);
const form_params = reactive({
  userId: null,
  userName: "",
  userRole: "admin",
  userAccount: "",
  userPasswd: null,
});
const form_rules = reactive({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  userRole: [{ required: true, message: "请选择角色", trigger: "change" }],
  userAccount: [{ required: true, message: "请输入账号", trigger: "blur" }],
  userPasswd: [{ required: true, message: "请输入密码", trigger: "blur" }],
});
const role_list = ref([
  {
    label: "管理员",
    value: "admin",
  },
  {
    label: "普通用户",
    value: "user",
  },
]);
const edit_info = ref({}); //当前编辑的数据
onMounted(() => {
  handleSearchList(); //获取列表数据
});

const handleSearchList = (type) => {
  if (type === "search") {
    search_params.pageNum = 1;
  }
  table_loading.value = true;
  AdminUserList(search_params)
    .then((res) => {
      table_list.value = res.list;
      table_total.value = res.total;
    })
    .finally(() => {
      table_loading.value = false;
    });
};
const handlePaginationChange = (value) => {
  search_params.pageNum = value.page;
  search_params.pageSize = value.size;
  handleSearchList();
};
const handleSearchReset = () => {
  search_params.queryParams.userName = "";
  search_params.queryParams.userAccount = "";
  search_params.queryParams.userStatus = "";
  handleSearchList("search");
};
const handleAddUser = () => {
  edit_info.value = {};
  form_params.userId = null;
  form_params.userName = "";
  form_params.userRole = "admin";
  form_params.userAccount = "";
  form_params.userPasswd = null;
  isShowDialog.value = true;
};
const handleEditUser = (item) => {
  edit_info.value = JSON.parse(JSON.stringify(item));
  form_params.userId = edit_info.value.userId;
  form_params.userName = edit_info.value.userName;
  form_params.userRole = edit_info.value.userRole;
  form_params.userAccount = edit_info.value.userAccount;
  dialog_state.value = false;
  isShowDialog.value = true;
};
const form_ref = ref(null);
const form_loading = ref(false);
const handleDialogClose = () => {
  edit_info.value = {};
  form_params.userId = null;
  form_params.userName = "";
  form_params.userRole = "admin";
  form_params.userAccount = "";
  form_params.userPasswd = null;
  nextTick(() => {
    dialog_state.value = true;
    form_ref.value.resetFields();
  });
  isShowDialog.value = false;
};
const handleDialogConfirm = () => {
  let obj = {};
  form_ref.value.validate((valid) => {
    if (valid) {
      if (dialog_state.value) {
        obj.userName = form_params.userName;
        obj.userRole = form_params.userRole;
        obj.userAccount = form_params.userAccount;
        obj.userPasswd = form_params.userPasswd;
        form_loading.value = true;
        AdminUserAdd(obj)
          .then((res) => {
            handleDialogClose();
            ElMessage.success("用户添加成功");
            handleSearchList();
          })
          .finally(() => {
            form_loading.value = false;
          });
      } else {
        form_loading.value = true;
        // 需要将所有数据都返回回去给后端
        obj = {
          ...edit_info.value,
        };
        obj.userName = form_params.userName;
        obj.userRole = form_params.userRole;
        obj.userAccount = form_params.userAccount;
        AdminUserEdit(obj)
          .then((res) => {
            handleDialogClose();
            ElMessage.success("用户编辑成功");
            handleSearchList();
          })
          .finally(() => {
            form_loading.value = false;
          });
      }
    }
  });
};
const handleStatusChange = (item) => {
  let text = "启用";
  if (item.userStatus == 1) text = "禁用";
  ElMessageBox.confirm(`确定要将该用户的状态修改为 ${text} 吗？`, "温馨提示", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning",
  })
    .then(() => {
      console.log(item);
      if (item.userStatus == 1) {
        item.userStatus = "-1";
      } else {
        item.userStatus = "1";
      }
      AdminUserEdit({ ...item })
        .then((res) => {
          ElMessage.success("用户状态编辑成功");
        })
        .finally(() => {
          handleSearchList();
        });
    })
    .catch(() => {});
};
const handleDelete = (item) => {
  ElMessageBox.confirm(`确定要删除将该用户吗？`, "温馨提示", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning",
  })
    .then(() => {
      let obj = {
        userId: item.userId,
      };
      AdminUserDelete(obj).then((res) => {
        ElMessage.success("用户删除成功");
        handleSearchList();
      });
    })
    .catch(() => {});
};
</script>
<style scoped lang="scss">
.main_block {
  height: 100%;
  width: 100%;
  background-color: #fff;
  padding: 10px;
}
.search_item {
  width: 200px;
  margin-right: 8px;
}
</style>
